package com.txsj.scan.presenter;

import android.os.Looper;

import com.greendao.GoodsInfoDao;
import com.txsj.scan.Constants;
import com.txsj.scan.base.BasePresenter;
import com.txsj.scan.bean.BaseListResult;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.InventoryBatchBean;
import com.txsj.scan.bean.RecordInfo;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.http.ApiServer;
import com.txsj.scan.http.requestframework.RetrofitManager;
import com.txsj.scan.utils.MD5Util;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.view.InventoryBatchIView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Created by WangChuangJun on 2018/11/21
 * @Describe
 */
public class InventoryBatchPresenter extends BasePresenter<InventoryBatchIView> {

    private WarehouseBean warehouseBean;
    private List<RecordInfo> recordInfoList;
    private long times_long = 1000*60*30;//时间差

    public InventoryBatchPresenter(InventoryBatchIView view) {
        super(view);
    }

    @Override
    protected void initModel() {
        recordInfoList = new ArrayList<>();
    }

    public void getBatchHttpData(long gs1_num, final int pageNo, String ware_house_id) {
        Map<String,String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID,0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN,""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("gs1_num", gs1_num+"");
        params.put("page", pageNo+"");
        params.put("limit", "20");
        params.put("warehouse_id", ware_house_id);
        view.onLoading();
        RetrofitManager.getDefault().create(ApiServer.class).goodsBatchInventory(RetrofitManager.getHeader(),params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseListResult<InventoryBatchBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseListResult<InventoryBatchBean> result) {
                        if (result.isSuccess()){
                            if (null != result.getData() && result.getData().size() > 0){
                                List<InventoryBatchBean> list = result.getData();
                                view.onSuccess(list);
                            }else {
                                if (pageNo == 1) {
                                    view.onError("暂无数据");
                                }else {
                                    view.onLoadEnd("加载完毕");
                                }
                            }
                        }else {
                            if (pageNo == 1){
                                view.onError("加载失败");
                            }else {
                                view.onLoadMoreError("加载失败");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (pageNo == 1){
                            view.onError("加载失败");
                        }else {
                            view.onLoadMoreError("加载失败");
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 缓存数据
     * @param warehouseBean
     */
    public void getGoodsListAndCache(WarehouseBean warehouseBean) {
        this.warehouseBean = warehouseBean;
        Map<String, String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("page", "0");
        params.put("limit", 200 + "");
        params.put("warehouse_id", warehouseBean.getWarehouse_id()+"");
        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
        params.put("sign", MD5Util.md5(params));//md5加密并加参数
        view.onLoading();
        RetrofitManager.getDefault().create(ApiServer.class).getGoodsInventoryList(RetrofitManager.getHeader(), params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.from(Looper.myLooper()))
                .subscribe(new Observer<BaseListResult<GoodsInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseListResult<GoodsInfo> result) {
                        if (result.isSuccess()) {
                            if (null != result.getData() && result.getData().size() > 0) {
                                List<GoodsInfo> list = result.getData();

                                setDataToDatabase(list);//缓存到本地
                                view.onCacheSuccess();

                            } else {
                                view.onError("网络异常");
                            }
                        } else {
                            view.onError("网络异常");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Trace.e("" + e.getMessage());
                        view.onError("网络异常");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void setDataToDatabase(List<GoodsInfo> goodsInfos) {
        GoodsInfoDao goodsInfoDao = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao();
        for (GoodsInfo goodsInfo : goodsInfos) {
            goodsInfo.setWarehouse_id(warehouseBean.getWarehouse_id()+"");//将请求回来的数据添加上warehouseid
            goodsInfoDao.insertOrReplace(goodsInfo);
        }

        //对更新后的数据进行记录
        if (null == recordInfoList || recordInfoList.size() == 0){
            RecordInfo recordInfo = new RecordInfo();
            recordInfo.setType(Constants.GOODS_INFO);
            recordInfo.setUpdate_time(System.currentTimeMillis());
            recordInfo.setWarehouse_id(warehouseBean.getWarehouse_id()+"");
            GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().insertOrReplace(recordInfo);
        }else {
            recordInfoList.get(0).setUpdate_time(System.currentTimeMillis());
            GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().insertOrReplace(recordInfoList.get(0));
            Trace.e("wcj最新更新时间：======"+recordInfoList.get(0).getUpdate_time());
        }
    }
}
